<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small"
          placeholder="输入员工姓名全员搜索" v-model="queryParams.keyword" @input="changValue" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" :data="depts" :props="defaultProps" default-expand-all
          :expand-on-click-node="false" highlight-current @current-change="selectNode" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column align="center" prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <el-avatar v-if="scope.row.staffPhoto" :size="30" :src="scope.row.staffPhoto"></el-avatar>
              <span class="username" v-else>{{ scope.row.username.charAt(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              <span v-if="scope.row.formOfEmployment === 1">正式</span>
              <span v-else-if="scope.row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确定删除改行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button style="margin-left: 10px;" slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px;" align="middle" type="flex" justify="end">
          <el-pagination :total="total" layout="total, prev, pager, next" :current-page.sync="queryParams.page"
            :page-size.sync="queryParams.pagesize" @current-change="changePage" />
        </el-row>
      </div>
    </div>
    <ImportExcel :showExcelDialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :label="item.id" :key="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { getEmployeeList, exportEmployee, delEmployee, getEnabledRoleList, getEmployeeDetail, assignRoles } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],// 部门树形数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //存储查询参数    
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      total: 0,//记录员工总数
      list: [],// 员工列表数据
      showExcelDialog: false,// 导入弹窗状态
      showRoleDialog: false,// 角色弹窗状态
      roleList: [],//角色列表数据
      roleIds: [],//用来双向保定
      currentUserId: null,// 当前用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      //这个时候参数 记录了id
      this.getEmployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 改变页码
    changePage(page) {
      this.queryParams.page = page
      this.getEmployeeList()
    },
    // 输入框值改变时 延迟300ms 重新请求
    changValue() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出功能
    async exportEmployee() {
      const result = await exportEmployee()// 导出功能
      // console.log(result)//使用一个npm包导出excel 
      FileSaver.saveAs(result, '员工信息.xlsx')// 下载文件
    },
    async confirmDel(id) {
      // 弹窗确认删除
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message({
        type: 'success',
        message: '员工删除成功!'
      })
    },
    // 弹窗显示角色
    async btnRole(id) {
      this.roleList = await getEnabledRoleList()
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async btnRoleOK() {
      await assignRoles({ id: this.currentUserId, roleIds: this.roleIds })
      this.$message({
        type: 'success',
        message: '角色分配成功!'
      })
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>